﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using Newtonsoft.Json;
using ProjectN.Core.Element;
using ProjectN.Core.Instance.Data;

namespace ProjectN.Core.Instance
{
    [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
    public class DynamicPage : DataSpreader, IPage, IDataModel
    {
        [Category("基本"), DisplayName("背景颜色"), DefaultValue(typeof(Color), "FFFFFFFF")]
        [JsonProperty] public Color BackgroundColor { get; set; } = Properties.Settings.Default.DefaultBGColor;

        [Browsable(false)]
        [JsonProperty] public Sequence<IElement> Elements { get; init; } = [];

        [Browsable(false)]
        public IEnumerable<IdPair<IElement>> IdentifiedElements => Elements;

        [Browsable(false)]
        IEnumerable<IElement> IPage.Elements => Elements;

        [Category("基本"), DisplayName("页面高度"), DefaultValue(100)]
        [JsonProperty] public int Height { get; set; } = 1;

        [Category("基本"), DisplayName("页面名称"), DefaultValue("未命名")]
        [JsonProperty] public string Identity { get; set; } = Properties.Resources.S_NO_ID;

        [Category("基本"), DisplayName("页面宽度"), DefaultValue(100)]
        [JsonProperty] public int Width { get; set; } = 1;

        [DisplayName("页面 GUID"), ReadOnly(true)]
        [JsonProperty] public Guid Guid { get; init; } = Guid.Empty;

        public event Action? OnUpdate;

        public void Update() => OnUpdate?.Invoke();

        public IElement? GetElement(int id)
        {
            return Elements.Contains(id)? Elements.Get(id): null;
        }

        public StaticPage ToStatic()
        {
            return new StaticPage([.. Elements], Width, Height, BackgroundColor, Identity, Guid);
        }

        public DynamicPage()
        {
            OnUpdate += () =>
            {
                if (Data != null)
                    UpdateData(Data);
            };
        }
        protected override void UpdateData(InstanceData data)
        {
            foreach (var element in Elements)
                element.OnLoad(data);
        }

        public override string ToString() => "页面";
    }
}
